<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\common\Pay;
use app\common\UserService;
use app\model\Shop;
use app\model\ShopOrders;
use app\model\User;
use app\tool\Random;
use think\db\Query;
use think\Exception;
use think\facade\Log;
use think\Request;

class ShopController extends BaseController
{
	function index()
	{
		$city_id = $this->request->get('city_id/d');
		$lat = $this->request->get('lat');
		$lng = $this->request->get('lng');
        if (empty($lat)||empty($lng)){
            $this->writeJson(0,'未获取经纬度');
        }
		Log::record($this->request->param());
		$rows = Shop::where(['status' => 2])
			->when(!empty($city_id), function (Query $query) use ($city_id) {
				$query->where(['city_id' => $city_id]);
			})
			->field("*,(6371 * acos (cos ( radians($lat) ) * cos( radians( lat ) ) * cos( radians(lng) - radians( $lng ) ) + sin ( radians( $lat ) ) * sin( radians( lat ) ))) AS distance")
			->filter(function ($data) use ($lat, $lng) {
				if (empty($lat) || empty($lng)) {
					$data->distance_text = '';
				} else {
					if ($data->distance == 0) {
						$data->distance_text = '0m';
					} elseif (0 < $data->distance && $data->distance < 1) {
						$data->distance_text = bcmul((string)$data->distance, '1000') . 'm';
					} else {
						$data->distance_text = bcmul((string)$data->distance, '1', 1) . 'km';
					}
				}
				
			})
			->order('distance', 'asc')
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	function detail()
	{
		$lat = $this->request->get('lat');
		$lng = $this->request->get('lng');
		$shop_id = $this->request->get('shop_id/d');
		
		$rows = Shop::field("*,(6371 * acos (cos ( radians($lat) ) * cos( radians( lat ) ) * cos( radians(lng) - radians( $lng ) ) + sin ( radians( $lat ) ) * sin( radians( lat ) ))) AS distance")
			->with(['user_collect' => function (Query $query) {
				$query->where(['user_id' => $this->user_id]);
			}])
			->filter(function ($data) use ($lat, $lng) {
				if (empty($lat) || empty($lng)) {
					$data->distance_text = '';
				} else {
					if ($data->distance == 0) {
						$data->distance_text = '0m';
					} elseif (0 < $data->distance && $data->distance < 1) {
						$data->distance_text = bcmul((string)$data->distance, '1000') . 'm';
					} else {
						$data->distance_text = bcmul((string)$data->distance, '1', 1) . 'km';
					}
				}
				
			})
			->findOrFail($shop_id);
		$this->writeJson($rows);
	}
	
	
	function collect()
	{
		$shop_id = $this->request->post('shop_id/d');
		$ret = UserService::collect($shop_id, $this->user_id, 3);
		$this->writeJson($ret);
	}
	
	function apply()
	{
		$name = $this->request->post('name');
		$mobile = $this->request->post('mobile');
		$city_id = $this->request->post('city_id/d');
		$address = $this->request->post('address');
		$opentime = $this->request->post('opentime');
		$content = $this->request->post('content');
		$image = $this->request->post('image');
		$images = $this->request->post('images');
		$invitecode = $this->request->post('invitecode');
		$lng = $this->request->post('lng');
		$lat = $this->request->post('lat');
        Log::record($this->request->post());

        if (empty($name)){
            $this->writeJson(0, '请输入门店名称');
        }
        if (empty($mobile)){
            $this->writeJson(0, '请输入联系方式');
        }
        if (empty($city_id)){
            $this->writeJson(0, '请选择城市');
        }
        if (empty($opentime)){
            $this->writeJson(0, '请输入营业时间');
        }
        if (empty($content)){
            $this->writeJson(0, '请输入商家介绍');
        }
        if (empty($image)){
            $this->writeJson(0, '请上传门店照');
        }
        if (empty($address)){
            $this->writeJson(0, '请输入详细地址');
        }
		if (empty($invitecode)){
			$this->writeJson(0, '请输入推广码');
		}
        if (empty($lng)||empty($lat)){
            $this->writeJson(0,'经纬度缺失');
        }
        if (empty($images)){
            $this->writeJson(0,'请上传详细照片');
        }
		
		$parent = User::where(['invitecode' => $invitecode])->find();
		if (!$parent) {
			$this->writeJson(0, '该推广员不存在');
		}
		
		$row = Shop::where(['user_id' => $this->user_id])->whereIn('status', [1, 2])->find();
		if ($row) {
			$this->writeJson(0, '请勿重复申请');
		}
		
		$data = [
			'name' => $name,
			'mobile' => $mobile,
			'city_id' => $city_id,
			'address' => $address,
			'opentime' => $opentime,
			'content' => $content,
			'image' => $image,
			'images' => $images,
			'user_id' => $this->user_id,
			'lng' => $lng,
			'lat' => $lat,
			'pid' => $parent->id
		];

		

		Shop::create($data);
		$this->writeJson();
	}
	
	function createOrder()
	{
		$pay_amount = $this->request->post('pay_amount');
		$shop_id = $this->request->post('shop_id/d');
		$shop = Shop::where(['status' => 2])->findOrFail($shop_id);
		$data = [
			'shop_id' => $shop->id,
			'user_id' => $this->user_id,
			'pay_amount' => $pay_amount,
			'order_sn' => Random::ordersn(),
		];
		$result = ShopOrders::create($data);
		$this->writeJson($result);
	}
	
	function orderPay()
	{
		$order_id = $this->request->post('order_id/d');
		$pay_type = $this->request->post('pay_type/d');#支付方式 1商家支付  2微信支付  3支付宝支付  4余额支付
		$password = $this->request->post('password');
		$order = ShopOrders::where(['user_id' => $this->user_id])->findOrFail($order_id);
		$user = User::find($this->user_id);
		try {
			if ($pay_type == 1) {
				if (empty($password)) {
					throw new Exception('请输入密码');
				}
				if ($order->shop->password != md5($password)) {
                    throw new Exception('密码错误');
				}
				UserService::changeUserMoney(-$order->pay_amount, $order->shop->user_id, '购买优惠券');
				app(NotifyController::class)->returnNotify(request()->setRoute(['paytype' => 'balance', 'out_trade_no' => $order->order_sn, 'attach' => 'shop']));
				$ret = true;
			} elseif ($pay_type == 2) {
				$ret = Pay::pay(1, $order->pay_amount, $order->order_sn, '购买优惠券', 'shop', $user->openid);
			} elseif ($pay_type == 3) {
				$ret = Pay::pay(2, $order->pay_amount, $order->order_sn, '购买优惠券', 'shop', $user->openid);
			} elseif ($pay_type == 4) {
				UserService::changeUserMoney(-$order->pay_amount, $user->id, '购买优惠券');
				app(NotifyController::class)->returnNotify(request()->setRoute(['paytype' => 'balance', 'out_trade_no' => $order->order_sn, 'attach' => 'shop']));
				$ret = true;
			} else {
                throw new Exception('支付方式错误');
			}
            $order->pay_source = request()->header('Client');
            $order->save();
		} catch (\Throwable $e) {
			$this->writeJson(0, $e->getMessage());
		}
		$this->writeJson($ret);
	}
	
	function getPayment()
	{
		$rows = ShopOrders::with(['shop'])->where(['user_id' => $this->user_id, 'status' => 2])->paginate()->items();
		$this->writeJson($rows);
	}
	
	
}
